import * as bm from "/js/baseModule.js";

require('/js/collapse.js');

export class Module extends bm.baseModule {
    constructor(view) {
        super(view);
        let that = this;
        this.proInfo = {};
        this.int1 = '';
        this.int2 = '';
        this.int3 = '';
        this.pointAtLeast = '';
        this.scope = this;
        this.isBomb = false;

        // 如果id不存在
        if (globalData.current_demand.id == '') {
            // 如果浏览器链接有did参数，则刷新
            if (funs.qs('did')) {
                window.location.reload();
            } else {
                location.hash = 'index';
            }
        }

        //详情页渲染
        let v_details = this.find('.DispatchDemand_vue')[0];
        let data = globalData;
        this.proInfo = new Vue({
            el: v_details,
            data: data,
            methods: {
                updateTime: function (startTime) {
                    startTime = startTime + '';
                    let text;
                    let stime = startTime * 1000;
                    let date = new Date().getTime();
                    let gapMin = Math.floor((date - stime) / 1000 / 60);
                    if (gapMin <= 0) {
                        //防止偶尔出现的js取时间不准确
                        gapMin = 1;
                    }
                    let gapHour = Math.floor((date - stime) / 1000 / 60 / 60);

                    if (gapHour <= 24) {
                        text = gapHour + '小时前';
                        if (gapMin < 60) {
                            text = gapMin + '分钟前';
                        }
                    } else if (gapHour <= 24 * 8) {
                        gapHour = Math.floor(gapHour / 24);
                        text = gapHour + '天前'
                    } else if (gapHour > 24 * 8) {
                        let ddd = new Date(startTime * 1000);
                        gapHour = (ddd.getMonth() + 1) + '-' + ddd.getDate();
                        text = gapHour
                    } else {
                        //防止意外情况，暂时如此处理
                        text = '刚刚'
                    }
                    return text;
                },
                /*搜索词*/
                sem: function (str) {
                    if (str) {
                        str = str.replace(/\'/g, '"');
                        let sem = JSON.parse(str);
                        return sem.word;
                    } else {
                        return "";
                    }
                },
                /*input修改时，隐藏错误提示*/
                inputFunc: function () {
                    that.find(".errorTip").hide();
                    let val = that.find('.offer-input').val();
                    if (parseInt(val) >= 200) {
                        //爆灯
                        that.find('.offer-input').val(200);
                    }
                    this.current_demand.curr_offer = that.find('.offer-input').val();

                },
            },

            computed: {
                // 竞价的工程上列表处理
                sList: function () {
                    let list = this.current_demand.supplier_list;
                    let status = this.current_demand.status;
                    if (list.length == 0) {
                        return []
                    } else {
                        // 旧订单特殊处理
                        let now = new Date().getTime();
                        if (this.current_demand.published_at < 1509968204) {
                            for (let i = 0; i < list.length; i++) {
                                list[i].succ_item = false;
                                list[i].info = '通话结束';
                                list[i].oldOrder = true;
                            }
                        } else {
                            //首轮竞价
                            if (status == '10') {
                                list[0].succ_item = true;
                                list[0].info = '暂时领先';
                                if (list[0].offer == 200) {
                                    list[0].info = '成就值较高,暂时领先';

                                }

                                // if (status == '15' || '20' || '30' || '100' || '200)
                            } else {
                                for (let i = 0; i < list.length; i++) {
                                    list[i].oldOrder = false;
                                    if (list[i].status == '130') {
                                        list[i].succ_item = false;
                                        list[i].info = '超时未联系';
                                        continue
                                    }
                                    if (list[i].status == '110' || list[i].status == '120') {
                                        list[i].succ_item = true;
                                        list[i].info = '待呼叫';
                                        continue
                                    }
                                    if (list[i].status == '150') {
                                        list[i].succ_item = true;
                                        list[i].info = '正在呼叫客户';
                                        continue
                                    }
                                    if (list[i].status == '200') {
                                        list[i].succ_item = true;
                                        list[i].info = '通话结束' + that.transTime(list[i].contact_seconds);
                                        if (list[i].contact_seconds <= 30) {
                                            list[i].info = '通话结束'
                                        }
                                        // 机器人通话时长低于60秒，显示通话结束；反之正常显示
                                        if (list[i].is_robot || list[i].contact_seconds <= 60) {
                                            list[i].info = '通话结束'
                                        }
                                        if (this.current_demand.for_gold) {
                                            list[i].info = '竞价成功';
                                        }
                                        continue
                                    }
                                    if (list[i].status == '10') {
                                        list[i].succ_item = false;
                                        list[i].info = '拟出局';
                                        if (status == '100' || status == '200') {
                                            list[i].info = '出局';
                                        }
                                    }
                                }
                            }
                        }
                        return list
                    }
                },
                //申报审核结果
                finish_info: function () {
                    let info, btn, evt = '';
                    let status = this.current_demand.user_finish_img_info.state;
                    switch (status) {
                        case -1:
                            info = '项目已完成？申报可提升等级';
                            btn = '申报';
                            evt = 'load@m/project/DeclareProject';
                            break;
                        case 0:
                            info = '已申报，结果将微信通知您';
                            btn = '审核中';
                            break;
                        case 1:
                            info = '恭喜，你的申报已审核通过';
                            btn = '审核通过';
                            break;
                        case 2:
                            info = '抱歉，你的反馈信息审核失败';
                            btn = '已驳回';
                            break;
                    }
                    return { info: info, btn: btn, evt: evt }
                },
                //申报审核结果
                feedback_info: function () {
                    let info, btn, evt = '';
                    let status = this.current_demand.feedback_info.feedback_status;
                    let my_follow_type = this.current_demand.my_follow_type;
                    switch (status) {
                        case 0:
                            info = '信息有误？反馈成功返还汇币';
                            btn = '反馈';
                            evt = 'openFeedbackDemand';
                            break;
                        case 3:
                            info = '已反馈，结果将微信通知您';
                            btn = '审核中';
                            break;
                        case 2:
                            info = '恭喜，你的反馈已审核通过';
                            btn = '审核通过';
                            if (my_follow_type == 1) {
                                btn = '已锁定';
                            }
                            break;
                        case 1:
                            info = '抱歉，你的反馈信息审核失败';
                            btn = '审核失败';
                            break;
                    }
                    if (this.current_demand.status == 200) {
                        evt = '';
                    }
                    return { info: info, btn: btn, evt: evt }
                },
                //第N次发布理由列表处理
                publish_remark_list: function () {
                    let count = this.current_demand.published_count;
                    let remark = JSON.parse(this.current_demand.publish_remark);
                    let list = [];
                    let aaa;
                    if (!remark) {
                        return
                    }
                    for (let i = 1; i <= count; i++) {
                        if (remark[i + '']) {
                            aaa = { 'inedx': i, 'val': remark[i + ''] };
                            list.push(aaa);
                        }
                    }
                    return list.reverse();
                }
            }
        });

        /**
         * 如果是直接进入当前页面，则先loading一会儿，等数据回来
         */
        if (globalData.entryPage == 'DispatchDemand') {
            this.find('.sendImgPending').removeClass('hide');
            let id = globalData.current_demand.id;
            api.getDemandInfo({ "id": id }, {
                succ: function (demand) {
                    $.extend(true, globalData.current_demand, demand);
                    that.find('.sendImgPending').addClass('hide');
                    that._init();
                },
                fail: function (json) {
                    //  如果是项目已被删除或者不存在
                    if (json.status = "41004002") {
                        funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                            mod.setType(9);
                        })
                    } else {
                        funs.tip(json.msg, '', 'fail');
                        setTimeout(function () {
                            that._evt_goback();
                        }, 2000)
                    }
                }
            });
        }
        //监听数据返回
        $(document).on('data_update', function () {
            // 如果是直接进入当前页面，且项目已被删除或者不存在，则回到项目大厅
            if (globalData.currPage == 'dispatchDemand' && globalData.current_demand.uid == '0000X') {
                //订单不可见
                funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                    mod.setType(9);
                })
            }
        });

        /** 折叠 */
        $('.collapse').collapse();
        $('.panel-collapse').on('show.bs.collapse', function () {
            // 展开执行一些动作...
            let panelCollapse = $(this);
            panelCollapse.parent().find('.icon-circle-down').addClass('rotate');
            panelCollapse.parent().find('.panel-heading').css('padding-bottom', '0');

        }).on('hide.bs.collapse', function () {
            // 折叠执行一些动作...
            let panelCollapse = $(this);
            panelCollapse.parent().find('.icon-circle-down').removeClass('rotate');
            panelCollapse.parent().find('.panel-heading').css('padding-bottom', '0.1rem');
        }).on('shown.bs.collapse', function () {
            // 执行一些动作...
            $('#DemandDetail').scrollTop($('#DemandDetail')[0].scrollHeight);
        });

        //项目浏览数+1
        api.demandAddScan({ "id": parseInt(globalData.current_demand.id) }, {
            succ: function () {
                console.log('项目浏览量+1');
                globalData.current_demand.scan_count += 1;
            }
        });

    }

    _init() {
        let that = this;
        //汇币的计算
        /** 定时任务：定时请求项目参与表，并更新相关数据 */
        let demand = globalData.current_demand;
        // 进行中的、进入抢单环节的、不为采购的、真实的、项目，才会更新数据
        if (demand.tag == 0 && demand.cate != '4' && (demand.status == '10' || demand.status == '11' || demand.status == '15' || demand.status == '20' || demand.status == '30')) {
            // 获取项目参与列表,更新参与表和项目状态
            window.clearInterval(this.int2);
            this.int2 = setInterval(function () {
                api.getParticInfo({ demand_id: globalData.current_demand.id }, {
                    succ: function (json) {
                        let list = json.partic_supplier_list;
                        let isSame = true;
                        let a = JSON.stringify(globalData.current_demand.supplier_list);
                        let b = JSON.stringify(list);
                        a = a.replace(/\"info\":\"[\u4e00-\u9fa5]{3,6}\"/g, '').replace(/\"succ\_item\":[a-z]{4,5}/g, '');
                        b = b.replace(/\"info\":\"[\u4e00-\u9fa5]{3,6}\"/g, '').replace(/\"succ\_item\":[a-z]{4,5}/g, '');
                        if (a != b) isSame = false;
                        globalData.current_demand.supplier_list.length = 0;
                        globalData.current_demand.supplier_list.push(...list);
                        globalData.current_demand.status = json.demand_status;
                        globalData.current_demand.has_max = json.has_max;
                        //找到自己的信息并更新项目参与状态
                        $.each(list, function (index, value) {
                            if (value.id == globalData.user.user_id) {
                                globalData.current_demand.supplier_partic_status = value.status;
                            }
                        });
                    }
                });
            }, 2000);
        }
    }

    //页面加载事件
    afterInstall() {
        let that = this;
        $('.panel-collapse').collapse('hide');
        if (globalData.entryPage != 'DispatchDemand') {
            this._init();
        }
        if (globalData.entryPage == 'DispatchDemand') {
            api.getUserInfo({
                succ: function (user) {
                    $.extend(globalData.user, user);
                    globalData.pack.uid = user.id;
                    funs.removeWelcome();
                    that.grabCount();
                }
            });
        }
        // 无论啥类型项目，都要去取参与列表
        api.getParticInfo({ demand_id: globalData.current_demand.id }, {
            succ: function (json) {
                let list = json.partic_supplier_list;
                globalData.current_demand.supplier_list.length = 0;
                globalData.current_demand.supplier_list.push(...list);
                globalData.current_demand.status = json.demand_status;
                //找到自己的信息并更新项目参与状态
                $.each(list, function (index, value) {
                    if (value.id == globalData.user.user_id) {
                        globalData.current_demand.supplier_partic_status = value.status;
                    }
                });
                //抢单倒计时
                that.grabCount();
            }
        });

    }

    /*==============录音音频处理-start=============*/

    //录音播放暂停
    _evt_playPause(target) {
        if (globalData.current_demand.supplier_partic_status != '200' && globalData.current_demand.audio_sensitive) {
            //audio_sensitive==true 敏感录音
            //未参与并且是敏感录音，弹一个提示气泡
            funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                mod.setType(7);
            });
            return;
        }

        let that = this;
        if (globalData.current_demand.tag != 0) {
            //虚拟订单不可播放
            return;
        }
        //如果录音加载失败
        let audioTime = this.find('.audio-time');
        let audio = document.getElementById("audioTag");
        if (audio.paused) {
            audio.play();
            this.find('.audio-time').removeClass('hide');
            this.find('.txt').addClass('hide');
            //改变icon
            $(target).find('.play-pause>span').removeClass('icon-play-one').addClass('icon-pause-one')
        } else {
            audio.pause();
            $(target).find('.play-pause>span').removeClass('icon-pause-one').addClass('icon-play-one')
        }

        //监听音频播放时间并更新进度条
        audio.addEventListener('timeupdate', function () {
            //更新进度条
            let audio = document.getElementsByTagName('audio')[0];
            // $('.audio-time').html(that.transTime(audio.duration - audio.currentTime));
            let rate = parseInt(audio.currentTime / audio.duration * 100 * 3.6);
            if (rate <= 180) {
                $('.circle_right').css('transform', 'rotate(' + rate + 'deg)');
            } else {
                $('.circle_right').css({
                    'transform': 'rotate(0deg)',
                    "background": "#f8d498"
                });
                $('.circle_left').css('transform', 'rotate(' + (rate - 180) + 'deg)');
            }
        }, false);
        //监听播放完成事件
        audio.addEventListener('ended', function () {
            //播放完成
            let audio = document.getElementsByTagName('audio')[0];
            audio.currentTime = 0;
            audio.pause();
            that.find('.play-pause>span').removeClass('icon-pause-one').addClass('icon-play-one');
            that.find('.audio-time').addClass('hide');
            that.find('.txt').removeClass('hide');
            $('.circle_right').css({
                'transform': 'rotate(0deg)',
                "background": "#FFECCD"
            });
            $('.circle_left').css('transform', 'rotate(0deg)');
        }, false);
    };

    //转换音频时长格式
    transTime(time) {
        let duration = parseInt(time);
        let minute = Math.floor(duration / 60);
        let sec = duration % 60 + '';
        let isM0 = ':';
        if (minute == 0) {
            minute = '00';
        } else if (minute < 10) {
            minute = '0' + minute;
        }
        if (sec.length == 1) {
            sec = '0' + sec;
        }
        return minute + isM0 + sec
    }

    /*==============录音音频处理-end=============*/

    //点击查看大图
    _evt_scanBig(obj) {
        let src = $(obj).attr('src');
        let width = $(obj).width();
        let height = $(obj).height();
        let rate = width / height;//宽高比
        let hh = $(window).width();//大图的宽 == 屏幕宽度
        let bgh = hh / rate / 2;  // 计算出大图的高度 de 一半

        //dom插入
        let bigImg = '<div class="bigImgBg" evt="closeBigImg"><img class="bigImg" src="' + src + '"/></div>';
        $(this.view).append(bigImg);

        //让图片垂直居中
        $('.bigImg').css('margin-top', -bgh + 'px');
    };

    _evt_closeBigImg(obj) {
        $(obj).remove();
    };

    /*================抢单逻辑－start===============
    * 当出价高于200时，最高为200，并只能出价一次，安装成就值高低排序
    */
    _evt_grab() {
        let that = this;
        let userInfo = globalData.user;
        let demandInfo = globalData.current_demand;
        let coin = 0;
        if (userInfo.user_type == 100) {
            if (userInfo.avatar) {
                /**弹出扣除次数 */
                coin = parseInt($('.offer-input').val());
                if (demandInfo.status == '20') {
                    coin = demandInfo.price;
                }
                if (coin >= 200 || that.isBomb) {
                    coin = 200;
                }
                funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                    mod.setType(20, { coin: coin });
                })

            } else {
                //弹出完善个人资料信息弹窗
                funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                    mod.setType(2);
                })
            }
        } else {
            // 游客，去登陆
            if (globalData.user.user_type == 0) {
                funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                    mod.setType(1);
                })

                // 客户,去完善资料
            } else if (globalData.user.user_type == 1) {
                funs.openModal('modules/modals/CommonModal.JS', function (mod) {
                    mod.setType(2);
                })
            }
        }
    }

    /*拨打电话方法*/
    _evt_fromWPH() {
        funs.openModal('modules/modals/CommonModal.js', function (mod) {
            mod.setType(6, { phone: globalData.current_demand.user.phone })
        })
    }


    // 页面卸载事件
    afterUninstall() {
        let that = this;
        // 如果录音存在，离开洽谈室时重置录音播放；
        if (globalData.current_demand.audio) {
            //播放完成
            let audio = document.getElementsByTagName('audio')[0];
            audio.currentTime = 0;
            audio.pause();
            this.find('.play-pause>span').removeClass('icon-pause-one').addClass('icon-play-one');
            this.find('.audio-time').addClass('hide');
            this.find('.txt').removeClass('hide');
        }
        //倒计时清空
        window.clearInterval(that.int1);
        window.clearInterval(that.int2);
        this.find('.count-deadline').text('');
        globalData.currPage = 'index';
    }

    //竞价项目倒计时
    grabCount() {
        let demand = globalData.current_demand;
        if (demand.cate == '4') return;
        let dl = demand.bid_win_at;
        if (!dl) return;
        dl = dl * 1000;
        let _time = 15;
        if (demand.is_training) { _time = 5 } else { _time = 15 }//派单倒计时15分钟，送单倒计时5分钟
        window.clearInterval(this.int3);
        this.int3 = setInterval(() => {
            let now = new Date().getTime() + 3000; // 计时器加3秒，以便保证计时结束时取接口信息时服务端已经更新
            let m, s;
            //获得跟当前时间的间隔秒数
            let gapSec = Math.floor((now - dl) / 1000);
            //如果超过15分钟
            if (gapSec > 60 * _time) {
                window.clearInterval(this.int3);
                $('.deadline').hide();
                return
            }
            gapSec = 60 * _time - gapSec;
            m = parseInt(gapSec / 60);
            if (m > 0) {
                s = gapSec - 60 * m;
            } else {
                s = gapSec;
            }
            if (m < 10) m = '0' + m;
            if (s < 10) s = '0' + s;

            let text = '00:' + m + ':' + s;
            $('.deadline').show();
            this.find('.count-deadline').text(text);

            //倒计时将结束时(2s)，重新取项目信息（做一个时间1秒的差）
            if (m == '00' && s == '02') {
                setTimeout(function () {
                    api.getDemandInfo({ "id": globalData.current_demand.id }, {
                        succ: function (demand) {
                            $.extend(true, globalData.current_demand, demand);
                        }
                    })
                }, 3100);
            }
        }, 1000);

    }

    /** 点击竞价规则滚动到页面底部 */
    _evt_scrollToRules() {
        $('#collapseFour').collapse('show');
        $('#DemandDetail').animate({ scrollTop: $('#DemandDetail')[0].scrollHeight }, 600);
    }

    /*反馈信息*/
    _evt_openFeedbackDemand() {
        let pro_info = globalData.current_demand;
        if (pro_info) {
            location.hash = 'project/FeedbackDemand?feedbackdemand=' + pro_info.id;
        }
    }

    _evt_goIndex() {
        location.hash = 'index';
    }

    _evt_loadRefunds() {
        location.hash = 'project/demand/Refunds';
    }
}
